package com.eigaland.change_machine.business.network

import com.eigaland.change_machine.APP
import com.eigaland.change_machine.util.UserManager
import com.eigland.eigaland_lib.model.Error
import com.eigland.eigaland_lib.model.BaseResp
import com.google.gson.Gson
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import com.orhanobut.logger.Logger
import movie6.posprintercept2.extensions.fromJson
import movie6.posprintercept2.extensions.getToken
import movie6.posprintercept2.extensions.saveToken
import okhttp3.*
import okio.Buffer
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.nio.charset.Charset
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

public class RetrofitClient{

    companion object {


        fun <T> getService(service: Class<T>,baseDomain:String): T {
            val trustAllCerts = arrayOf<TrustManager>(
                object : X509TrustManager {
                    override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
                    }

                    override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
                    }

                    override fun getAcceptedIssuers(): Array<X509Certificate> {
                        return arrayOf()
                    }
                }
            )
            var sslContext = SSLContext.getInstance("SSL")
            sslContext.init(null, trustAllCerts, SecureRandom())
            var clien = OkHttpClient.Builder()
                //自定义拦截器用于日志输出
                .retryOnConnectionFailure(true)
                .addInterceptor(LogInterceptor())
                .sslSocketFactory(sslContext.socketFactory, trustAllCerts[0] as X509TrustManager)
                .build()

            val retrofit = Retrofit.Builder().baseUrl(baseDomain)
                //格式转换=
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(CoroutineCallAdapterFactory.invoke())
                .client(clien)
                .build()
            return retrofit.create(service)
        }


    }

}
class LogInterceptor: Interceptor {


    override fun intercept(chain: Interceptor.Chain): Response {

        var request =
            if(APP.app.getToken().isNotEmpty() && !chain.request().url().toString().contains("login") && !chain.request().url().toString().contains("register"))
                chain.request().newBuilder().addHeader("Authorization","Bearer " + APP.app.getToken()).build()  else chain.request()
        val copy = request.newBuilder().addHeader("Authorization","Bearer 6666").build()
        val b = Buffer()
        copy.headers()
        copy.body()?.writeTo(b)

        //TODO make header

        val response = chain.proceed(request)
        var copyBody = response.peekBody(1024 * 1024 * 2)
        var bodyStr = ""
        if(copyBody != null) {
            var s = copyBody.source()
            s.request(Long.MAX_VALUE)
            var b = s.buffer
            bodyStr = b.clone().readString(Charset.forName("UTF-8"))

        }

        Logger.e(bodyStr)
        Logger.e("Requesting: ${request.method()} ${request.url()}\nHeader: ${request.headers()}")

        if(response.code() == 500) { // send error to every page

            Logger.json(Gson().toJson(bodyStr))


            var result = BaseResp<Nothing>()
            result.error = Gson().fromJson(bodyStr,Error::class.java)

            return response.newBuilder().code(200).body(ResponseBody.create(MediaType.parse("application/json"),Gson().toJson(result))).build()

        }  else {
            var result = BaseResp<Any>()
            result.error = null
            result.success = Gson().fromJson(bodyStr)

            Logger.json(Gson().toJson(result))

            Logger.e(
                "收到响应 %s%s %ss\n请求url：%s\nAuthorization：%s\n请求body：%s",
                response.code(),
                response.message(),
                1,
                response.request().url(),
                copy?.headers()?.get("Authorization") ?: "",
                (if (copy.body()?.contentLength() ?: 0L != 0L) b.readUtf8() else "").trimMargin()
            )

            return response.newBuilder().code(200).body(ResponseBody.create(MediaType.parse("application/json"),Gson().toJson(result))).build()
        }
    }



}